﻿# data/akshare_loader.py
import akshare as ak
import pandas as pd

def fetch_stock_data(symbol: str, start_date: str, end_date: str):
    try:
        df = ak.stock_zh_a_hist(
            symbol=symbol,
            period="daily",
            start_date=start_date,
            end_date=end_date,
            adjust="qfq"
        )
        if df.empty:
            raise ValueError("数据为空")

        # 重命名列名以匹配 backtrader
        df.rename(columns={
            "收盘": "close",
            "开盘": "open",
            "最高": "high",
            "最低": "low",
            "成交量": "volume"
        }, inplace=True)

        df["date"] = pd.to_datetime(df["日期"])
        df.set_index("date", inplace=True)
        df = df[["open", "high", "low", "close", "volume"]].astype(float)
        return df
    except Exception as e:
        print(f"数据获取失败: {e}")
        return pd.DataFrame()